package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author by mycp
 * @Classname LoginController
 * @Description TODO
 * @Date 2018/11/1 16:21
 */
@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;
    /**
     * 资源: /sessions
     * 动作: POST
     * 参数: email = xx & password=xx
     *
     * @RequestParam: 表示浏览器必须要出入对应的参数才能访问
     */
    @PostMapping
    @ResponseBody
    public Object login(@RequestParam String password, @RequestParam String email){
        JsonResult result = new JsonResult();
        try {
            // 调用service登录验证的方法, 进行登录验证
            User user = userService.login(password, email);
            result.setData(user);
            // 设置用户信息到session中
            UserContext.setCurrentUser(user);

        } catch (Exception e) {
            e.printStackTrace();
            // 如果登录失败, 设置失败信息
            result.mark(e.getMessage());
        }
        // 返回JsonResult对象给前台
        return result;
    }

    /**
     * 注销
     */
    @DeleteMapping
    @ResponseBody
    public void loginOut(HttpServletResponse resp, HttpSession session){
        // 注销session
        session.invalidate();
        // 设置响应状态码
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }

}
